package io.github.fb513.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.github.fb513.api.entity.Message;
import io.github.fb513.api.entity.UserMessage;
import io.github.fb513.api.mapper.MessageMapper;
import io.github.fb513.api.mapper.UserMessageMapper;
import io.github.fb513.api.model.response.OfflineMsgResp;
import io.github.fb513.api.service.IUserMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.fb513.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户的消息表 服务实现类
 * </p>
 *
 * @author fengbo
 * @since 2023-12-27
 */
@Service
public class UserMessageServiceImpl extends ServiceImpl<UserMessageMapper, UserMessage> implements IUserMessageService {


    @Autowired private MessageMapper messageMapper;

    @Override public List<OfflineMsgResp> getMessageList(Long userId, Long sourceId, Long maxMsgId, Long minMsgId) {
        List<UserMessage> userMessageList = list(new LambdaQueryWrapper<UserMessage>()
                .eq(UserMessage::getOwnerId, userId).eq(UserMessage::getSourceId, sourceId)
                .lt(maxMsgId != null, UserMessage::getId, maxMsgId)
                .gt(minMsgId != null, UserMessage::getId, minMsgId)
                .orderByDesc(UserMessage::getId)
                .last("limit 20")
        );
        List<Long> messageIds = userMessageList.stream().map(UserMessage::getMessageId).toList();
        Map<Long, Message> messageMap = Collections.emptyMap();
        if (!CollectionUtils.isEmpty(messageIds)) {
            messageMap = messageMapper.selectBatchIds(messageIds).stream().collect(Collectors.toMap(Message::getId, Function.identity()));
        }
        List<OfflineMsgResp> respList = new ArrayList<>(userMessageList.size());
        for (UserMessage userMessage : userMessageList) {
            OfflineMsgResp resp = new OfflineMsgResp();
            resp.setMessageId(userMessage.getId());
            resp.setSourceId(userMessage.getSourceId());
            resp.setSourceType(userMessage.getSourceType());
            resp.setCreatedOn(DateUtils.convertToMillis(userMessage.getCreatedOn()));
            resp.setMessageStatus(userMessage.getMessageStatus());
            Message message = messageMap.get(userMessage.getMessageId());
            resp.setMessage(message.getMessageInfo());
            resp.setClientId(message.getClientId());
            resp.setMessageType(message.getMessageType());
            respList.add(resp);
        }
        return respList;
    }

}
